<!--
 * @Author: early-autumn
 * @Date: 2020-05-03 19:55:11
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 16:01:01
 -->
<template>
  <el-popover v-model="visible" width="500" placement="bottom">
    <el-checkbox-group v-model="values" @change="handleFilter">
      <el-row>
        <el-col v-for="column in columns" :key="column" :span="8">
          <el-checkbox :label="column">{{ column }}</el-checkbox>
        </el-col>
      </el-row>
    </el-checkbox-group>
    <el-button slot="reference" :type="type" icon="el-icon-sort" :size="size">
      筛选列
    </el-button>
  </el-popover>
</template>

<script>
import { DEFAULT_NAME, getId, getValues, setValues } from './util'
import event from './event'

export default {
  name: 'ColumnsFilterButton',
  props: {
    // 名称
    name: {
      type: String,
      default: DEFAULT_NAME,
    },
    size: {
      type: String,
      default: 'medium',
    },
    type: {
      type: String,
      default: 'primary',
    },
  },
  data() {
    return {
      // 显示隐藏
      visible: false,
      // 当前 id
      id: '',
      // 选择值
      values: [],
      columns: [],
      table: null,
    }
  },
  created() {
    this.id = getId(this.name)
  },
  mounted() {
    this.table = this.findTable()
    this.init()
  },
  destroyed() {
    event.off(this.id)
  },
  methods: {
    findTable() {
      let parent = this.$parent
      while (parent !== null) {
        for (let children of parent.$children) {
          if (children.$options.name === 'ElTable') {
            return children
          }
        }
        parent = parent.$parent
      }
      throw new Error('ColumnsFilterButton: 当前页面不存在 el-table 组件')
    },
    init() {
      const values = getValues(this.id)
      this.$nextTick(() => {
        this.columns = this.table.$children
          .map((children) => children.ident)
          .filter((i) => !!i)
        this.values = values !== null ? values : this.columns
      })
    },
    handleFilter() {
      setValues(this.id, this.values)
      event.emit(this.id, this.values)
    },
  },
}
</script>

<style lang="scss" scoped>
.line {
  margin: 10px 0;
}

.button-group {
  display: flex;
  justify-content: flex-end;

  & > button {
    padding: 0px;
    height: 20px;
    line-height: 20px;
  }
}
</style>
